package com.xgkj.diyiketang.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.data.DatiInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.DatiDetailTask;
import com.xgkj.diyiketang.task.PostMyAnswerTask;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.weidget.NestRadioGroup;

import java.util.ArrayList;
import java.util.List;

public class DatiDetailActivity extends BaseActivity implements View.OnClickListener,NestRadioGroup.OnCheckedChangeListener{
    private Context mContext;
    private RelativeLayout titleLayout;
    private TextView back;
    private RatingBar scoreLayout;
    private ImageView datiImage;
    private NestRadioGroup daanRadiogroup;
    private RadioButton daanA;
    private ImageView duigouA;
    private RadioButton daanB;
    private ImageView duigouB;
    private RadioButton daanC;
    private ImageView duigouC;
    private RadioButton daanD;
    private ImageView duigouD;
    private LinearLayout jiexiLayout;
    private ImageView jiexiImage;
    private boolean isFirst = false;
    private String myAnswer;
    private DatiInfo datiInfo;
    private String questionId;
    private int myScore;
    private int answerquestionId = -1;
    private int datiDetailTaskId = -1;
    private EditText tiankongEdit;
    private Button okBtn;
    private ViewUtil.Size size;
    private String cla;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dati_detail);
        mContext = this;
        size = new ViewUtil.Size(ViewUtil.getScreenWidth(mContext),0);
        initView();
        getDatiDetail();
    }

    private void initView() {
        Intent intent = getIntent();
        if (intent != null){
            datiInfo = (DatiInfo) intent.getSerializableExtra("DATIINFO");
            cla = intent.getStringExtra("BANJI");
            questionId = datiInfo.getQuestionId();
        }
        titleLayout = (RelativeLayout) findViewById(R.id.title_layout);
        back = (TextView) findViewById(R.id.back);
        back.setOnClickListener(this);
        scoreLayout = (RatingBar) findViewById(R.id.score_layout);
        datiImage = (ImageView) findViewById(R.id.dati_image);
        datiImage.setOnClickListener(this);
        tiankongEdit = (EditText) findViewById(R.id.tiankongEdit);
        okBtn = (Button) findViewById(R.id.ok_btn);
        okBtn.setOnClickListener(this);
        daanRadiogroup = (NestRadioGroup) findViewById(R.id.daan_radiogroup);
        daanRadiogroup.setOnCheckedChangeListener(this);
        daanA = (RadioButton) findViewById(R.id.daan_a);
        duigouA = (ImageView) findViewById(R.id.duigou_a);
        daanB = (RadioButton) findViewById(R.id.daan_b);
        duigouB = (ImageView) findViewById(R.id.duigou_b);
        daanC = (RadioButton) findViewById(R.id.daan_c);
        duigouC = (ImageView) findViewById(R.id.duigou_c);
        daanD = (RadioButton) findViewById(R.id.daan_d);
        duigouD = (ImageView) findViewById(R.id.duigou_d);
        jiexiLayout = (LinearLayout) findViewById(R.id.jiexi_layout);
        jiexiImage = (ImageView) findViewById(R.id.jiexi_image);
        jiexiImage.setOnClickListener(this);
        jiexiLayout.setVisibility(View.GONE);
        if (datiInfo.getQuestionType().equalsIgnoreCase("0")){
            //填空
            daanRadiogroup.setVisibility(View.GONE);
            tiankongEdit.setVisibility(View.VISIBLE);
            tiankongEdit.setEnabled(false);
            okBtn.setVisibility(View.GONE);
        }else if (datiInfo.getQuestionType().equalsIgnoreCase("1")){
            //选择
            daanRadiogroup.setVisibility(View.VISIBLE);
            tiankongEdit.setVisibility(View.GONE);
            okBtn.setVisibility(View.GONE);
            disabledRadioGroup();
        }
    }

    private void updateView(){
        scoreLayout.setNumStars(datiInfo.getRewardCount());
        ImageCache.getInstance(mContext).loadBitmapToView(datiImage,datiInfo.getQuestionImage(),size);
        if (datiInfo.getCanAnswer()){
            if (datiInfo.getQuestionType().equalsIgnoreCase("0")){
                //填空
                tiankongEdit.setEnabled(true);
                okBtn.setVisibility(View.VISIBLE);
                if (datiInfo.getUserAnswer() != null){
                    tiankongEdit.setText(datiInfo.getUserAnswer());
                    tiankongEdit.setEnabled(false);
                    okBtn.setVisibility(View.GONE);
                    jiexiLayout.setVisibility(View.VISIBLE);
                    ImageCache.getInstance(mContext).loadBitmapToView(jiexiImage,datiInfo.getAnalyze(),size);
                }
            }else if (datiInfo.getQuestionType().equalsIgnoreCase("1")){
                //选择
                enableRadioGroup();
                String rightAnswer = datiInfo.getUserAnswer();
                if (rightAnswer != null){
                    if (rightAnswer.equalsIgnoreCase("A")){
                        daanA.setChecked(true);
                    }else if (rightAnswer.equalsIgnoreCase("B")){
                        daanB.setChecked(true);
                    }else if (rightAnswer.equalsIgnoreCase("C")){
                        daanC.setChecked(true);
                    }else if (rightAnswer.equalsIgnoreCase("D")){
                        daanD.setChecked(true);
                    }
                }

            }
        }else {
            ToastUtil.showMessage(mContext,R.string.you_no_flower);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        getDatiDetail();
    }


    private void getDatiDetail() {
        DatiDetailTask datiDetailTask = new DatiDetailTask(questionId);
        datiDetailTask.addListener(mListener);
        datiDetailTaskId = getEatShowApp().getTaskManager().addTask(datiDetailTask);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
                finish();
                break;
            case R.id.dati_image:
                Intent dati_big_intent = new Intent(mContext,ShowBigImageActivity.class);
//                dati_big_intent.putExtra("BIGIMAGE",datiInfo.getQuestionImage());
//                startActivity(dati_big_intent);
                String bigImage = datiInfo.getQuestionImage();
                ArrayList<String> adlist = new ArrayList<String>();
                adlist.add(bigImage);
                dati_big_intent.putExtra("photoList",adlist);
                dati_big_intent.putExtra("currentPosition", 0);
                startActivity(dati_big_intent);
                break;
            case R.id.jiexi_image:
                Intent jiexi_big_intent = new Intent(mContext,ShowBigImageActivity.class);

                String bigImage1 = datiInfo.getAnalyze();
                ArrayList<String> adlist1 = new ArrayList<String>();
                adlist1.add(bigImage1);
                jiexi_big_intent.putExtra("photoList",adlist1);
                jiexi_big_intent.putExtra("currentPosition", 0);
                startActivity(jiexi_big_intent);
//                jiexi_big_intent.putExtra("BIGIMAGE",datiInfo.getAnalyze());
//                startActivity(jiexi_big_intent);
                break;
            case R.id.ok_btn:
                myAnswer = tiankongEdit.getText().toString();
                if (ViewUtil.isNull(myAnswer)){
                    ToastUtil.showMessage(mContext,R.string.please_write_your_answer);
                    return;
                }

                if (myAnswer.equalsIgnoreCase(datiInfo.getRightAnswer())){
                    myScore = datiInfo.getRewardCount();
                }else {
                    myScore = -1;
                }
                InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                im.hideSoftInputFromWindow(DatiDetailActivity.this.getCurrentFocus().getWindowToken(),0);
                postMyAnswer();
                okBtn.setVisibility(View.GONE);

                jiexiLayout.setVisibility(View.VISIBLE);
                ImageCache.getInstance(mContext).loadBitmapToView(jiexiImage,datiInfo.getAnalyze(),size);
                break;
        }

    }

    @Override
    public void onCheckedChanged(NestRadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.daan_a:
                myAnswer = "A";
                compareAnswer();
                break;

            case R.id.daan_b:
                myAnswer = "B";
                compareAnswer();
                break;

            case R.id.daan_c:
                myAnswer = "C";
                compareAnswer();
                break;

            case R.id.daan_d:
                myAnswer = "D";
                compareAnswer();
                break;

            default:

                break;
        }
    }

    public void compareAnswer(){
        if (datiInfo == null) {
            daanA.setChecked(false);
            daanB.setChecked(false);
            daanC.setChecked(false);
            daanD.setChecked(false);
            return;
        }
        if (myAnswer.equalsIgnoreCase(datiInfo.getRightAnswer())){
            refreshAnswer(0);
        }else {
            refreshAnswer(1);
        }
        disabledRadioGroup();
    }

    private void disabledRadioGroup(){
        final List<CompoundButton> list = findCheckedView(daanRadiogroup);
        for (CompoundButton view : list) {
            if (view != null) {
                view.setEnabled(false);
            }
        }
    }

    private void enableRadioGroup(){
        List<CompoundButton> list = findCheckedView(daanRadiogroup);
        for (CompoundButton view :list){
            if (view != null){
                view.setEnabled(true);
            }
        }
    }

    private static List<CompoundButton> findCheckedView(View child) {
        List<CompoundButton> allButton = new ArrayList<CompoundButton>();
        if (child instanceof CompoundButton){
            allButton.add((CompoundButton) child);
            return allButton;
        }

        if (child instanceof ViewGroup) {
            ViewGroup group = (ViewGroup) child;
            for (int i = 0, j = group.getChildCount(); i < j; i++) {
                List<CompoundButton>allChildBtn = findCheckedView(group.getChildAt(i));
                if (allChildBtn != null && allChildBtn.size()>0){
                    allButton.addAll(allChildBtn);
                }
            }
            return allButton;
        }
        return null;//没有找到
    }

    private void refreshAnswer(int type){


            if (datiInfo.getRightAnswer().equalsIgnoreCase("A")){
                daanA.setBackgroundResource(R.drawable.daan_bg_dui);
                daanA.setTextColor(getResources().getColor(R.color.shouye_tab_color_selected));
                duigouA.setImageResource(R.drawable.daan_dui);
                duigouA.setVisibility(View.VISIBLE);
            }

            if (datiInfo.getRightAnswer().equalsIgnoreCase("B")){
                daanB.setBackgroundResource(R.drawable.daan_bg_dui);
                daanB.setTextColor(getResources().getColor(R.color.shouye_tab_color_selected));
                duigouB.setImageResource(R.drawable.daan_dui);
                duigouB.setVisibility(View.VISIBLE);
            }

            if (datiInfo.getRightAnswer().equalsIgnoreCase("C")){
                daanC.setBackgroundResource(R.drawable.daan_bg_dui);
                daanC.setTextColor(getResources().getColor(R.color.shouye_tab_color_selected));
                duigouC.setImageResource(R.drawable.daan_dui);
                duigouC.setVisibility(View.VISIBLE);
            }

            if (datiInfo.getRightAnswer().equalsIgnoreCase("D")){
                daanD.setBackgroundResource(R.drawable.daan_bg_dui);
                daanD.setTextColor(getResources().getColor(R.color.shouye_tab_color_selected));
                duigouD.setImageResource(R.drawable.daan_dui);
                duigouD.setVisibility(View.VISIBLE);
            }
        myScore = datiInfo.getRewardCount();

         if (type ==1){
             myScore = -1;
            if (myAnswer.equalsIgnoreCase("A")){
                duigouA.setImageResource(R.drawable.daan_cuo);
                daanA.setBackgroundResource(R.drawable.daan_bg_cuo);
                daanA.setTextColor(getResources().getColor(R.color.over_orange));
                duigouA.setVisibility(View.VISIBLE);
            }

            if (myAnswer.equalsIgnoreCase("B")){
                duigouB.setImageResource(R.drawable.daan_cuo);
                daanB.setBackgroundResource(R.drawable.daan_bg_cuo);
                daanB.setTextColor(getResources().getColor(R.color.over_orange));
                duigouB.setVisibility(View.VISIBLE);
            }

            if (myAnswer.equalsIgnoreCase("C")){
                duigouC.setImageResource(R.drawable.daan_cuo);
                daanC.setBackgroundResource(R.drawable.daan_bg_cuo);
                daanC.setTextColor(getResources().getColor(R.color.over_orange));
                duigouC.setVisibility(View.VISIBLE);
            }

            if (myAnswer.equalsIgnoreCase("D")){
                duigouD.setImageResource(R.drawable.daan_cuo);
                daanD.setBackgroundResource(R.drawable.daan_bg_cuo);
                daanD.setTextColor(getResources().getColor(R.color.over_orange));
                duigouD.setVisibility(View.VISIBLE);
            }
        }
        if (ViewUtil.isNull(datiInfo.getUserAnswer())) {
            postMyAnswer();
        }

        jiexiLayout.setVisibility(View.VISIBLE);
        ImageCache.getInstance(mContext).loadBitmapToView(jiexiImage,datiInfo.getAnalyze(),size);

    }

    private void postMyAnswer(){
        PostMyAnswerTask task = new PostMyAnswerTask(questionId,myAnswer,myScore);
        task.addListener(mListener);
        answerquestionId = getEatShowApp().getTaskManager().addTask(task);

    }

    private TaskEventListener mListener = new ShowToastTaskEventListener(this){
        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (answerquestionId == taskId){

            }else if (taskId == datiDetailTaskId){
                if (data != null){
                    datiInfo = (DatiInfo) data;
                    questionId = datiInfo.getQuestionId();
                    myAnswer = datiInfo.getUserAnswer();
                    myScore = datiInfo.getRewardCount();
                }
                updateView();
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (taskId == datiDetailTaskId ){
                finish();
            }
        }
    };

}
